package com.liuhung.ash.security.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.liuhung.base.web.BaseAction;
import com.liuhung.base.util.HtmlUtil;
import com.liuhung.ash.security.entity.Role;
import com.liuhung.ash.security.entity.RolePermission;
import com.liuhung.ash.security.entity.Users;
import com.liuhung.ash.security.page.RolePage;
import com.liuhung.ash.security.page.UsersPage;
import com.liuhung.ash.security.service.RolePermissionService;
import com.liuhung.ash.security.service.RoleService;
/**
 * 
 * <br>
 * <b>功能：</b>RoleController<br>
 */
@Controller
@RequestMapping("/admin/security/role")
public class RoleController extends BaseAction {

	private final static Logger log = Logger.getLogger(RoleController.class);

	// Servrice start
	@Autowired(required = false)
	// 自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private RoleService roleService;
	@Autowired(required=false)
	private RolePermissionService rolePermissionService;

	/**
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request) throws Exception {
		RolePage page = new RolePage();
		Map<String, Object> context = getRootMap();
		List<Role> roles = roleService.queryByList(page);
		context.put("list", roles);
	
		return forword("com/liuhung/ash/security/role/list", context);
	}

	/**
	 * 页面数据datatable展示 所需json
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/data")
	public Map<String, Object> datalist(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer draw = getIntegerParameter(request,"draw");
		Integer start = getIntegerParameter(request,"start");
		Integer length =  getIntegerParameter(request,"length");
		Integer orderColumn =getIntegerParameter(request,"order[0][column]");
		String orderDir = request.getParameter("order[0][dir]");
		String searchValue = request.getParameter("search[value]");
		
		
		RolePage page = new RolePage();
		if(start!=null&&length!=null)
		{
			int pageId =start/length+ 1;
			page.setPage(pageId);
			page.setRows(length);
		}
		String orderField ="";
		if(orderColumn!=null)
		{
			switch (orderColumn) {
			case 1:
				orderField = "id";
				break;
			case 2:
				orderField = "name";
				break;
			case 3:
				orderField = "enname";
				break;
			case 4:
				orderField = "remark";
				break;
			case 5:
				orderField = "typeid";
				break;
			default:
				orderField = "id";
				break;
			}
		}	
		page.setSort(orderField);
		if(orderDir!=null)
			page.setOrder(orderDir.equals("asc")?0:1);
		int num=roleService.queryByCount(page);
		page.setNum(num);
		List<Role> dataList = roleService.queryByList(page);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("draw", draw);
		map.put("start",start);
		map.put("length", length);
		map.put("data", dataList);
		map.put("recordsTotal",num);//未过滤的数据条数
		map.put("recordsFiltered",num);//过滤的数据条数
		return map;
	}

	/**
	 * 数据ztree展示所需json
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/tree")
	public void datalistForTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RolePage page = new RolePage();
		page.setRows(10000);
		List<Role> dataList = roleService.queryByList(page);
		HtmlUtil.writerJson(response, dataList);
	}

	/**
	 * 添加或修改数据
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public void save(@RequestParam String id,
			@RequestParam String name,
			@RequestParam String remark,
			@RequestParam String permissions,
			HttpServletRequest request, HttpServletResponse response) {
		Role entity = new Role();
		entity.setName(name);
		entity.setRemark(remark);
		try {
			if (id == null || StringUtils.isBlank(id)){
				roleService.add(entity);
				
			} else {
				entity.setId(Integer.parseInt(id));
				roleService.update(entity);
			}
			String [] permissionsArr = permissions.split(",");
			if(permissionsArr.length>0)
			{
				//删除原有的所有从属权限
				rolePermissionService.deleteWithRid(entity.getId());
				//将最新的权限添加进去
				for(String pid:permissionsArr)
				{
					RolePermission rp=new RolePermission();
					rp.setRid(entity.getId());
					rp.setPid(Integer.parseInt(pid));
					rolePermissionService.add(rp);
				}
			}
			log.debug("Role对象保存成功！");
			sendSuccessMessage(response, "保存成功");
		} catch (Exception e) {
			sendFailureMessage(response, e.getMessage());
		}
		
		
	}
	@RequestMapping("/{id}")
	public void getId(@PathVariable String id, HttpServletResponse response) throws Exception {
		Map<String, Object> context = new HashMap<String, Object>();
		Role entity = roleService.queryById(id);
		if (entity == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", entity);
		HtmlUtil.writerJson(response, context);
	}
	@RequiresPermissions("role:delete")
	@RequestMapping("/delete")
	public void delete(@RequestParam("id") String ids,
			HttpServletResponse response,
			final RedirectAttributes redirectAttributes) throws Exception {
		String[] id = ids.split(",");
		roleService.delete(id);
		sendSuccessMessage(response, "删除成功");
		
	}

}
